package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.repository.query.ExampleQueryMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: WangPeiLin
 * @Description: 类内容说明
 * @Date: Created in 22:28 2021/1/2
 * @ModifiedBy:
 */
@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private PicUploadService picUploadService;

    /**
     * 保存用户其他信息
     *
     * @param param
     * @param token
     * @return
     */
    public Boolean saveUserInfo(Map<String, String> param, String token) {
        //校验token
        User user=this.userService.queryUserToken(token);
        if(null==user){
            //保存失败
            return false;
        }

        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"),"man")? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        return this.userInfoMapper.insert(userInfo)==1;
    }

    /**
     * 保存用户头像
     *
     * @param file
     * @param token
     * @return
     */
    public Boolean saveUserLogo(MultipartFile file, String token) {
        //校验token
        User user=this.userService.queryUserToken(token);
        if(null==user){
            //保存失败
            return false;
        }
        try {
            //校验图片是否为人脸,不是返回false
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if(!b){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //是人像把图片上传到阿里云的oss
        PicUploadResult result = this.picUploadService.upload(file);
        //判断图片是否上传成功
        if(StringUtils.isEmpty(result.getName())){
            return false;
        }
        //上传成功后把图像保存到对象中
        UserInfo userInfo=new UserInfo();
        userInfo.setLogo(result.getName());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return this.userInfoMapper.update(userInfo, queryWrapper) == 1;


    }
}
